package org.yys.producer.service.impl;

import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.yys.producer.domain.MsgDomain;
import org.yys.producer.service.FastTestService;

import java.util.Arrays;
import java.util.List;

@Service
public class FastTestServiceImpl implements FastTestService {
    @Autowired
    RocketMQTemplate rocketMQTemplate;

    @Override
    public void sendFastMsg() {
        rocketMQTemplate.syncSend("fastTopic","这是一条简单信息");
    }

    @Override
    public void sendAsync() {
        rocketMQTemplate.asyncSend("asyncTopic","这是一条异步消息", new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("异步消息发送成功");
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println("异步消息发送失败");
            }
        });
    }

    @Override
    public void sendOneway() {
        rocketMQTemplate.sendOneWay("onewayTopic","一条单向消息");
    }

    @Override
    public void sendDelay() {
        Message<String> message= MessageBuilder.withPayload("一条延时消息").build();
        rocketMQTemplate.syncSend("delayTopic", message, 3000,3);
    }

    @Override
    public void sendBatch() {

    }

    @Override
    public void sendOrderly() {
        List<MsgDomain> msgList= Arrays.asList(
                new MsgDomain("order1",1L,"下单"),
                new MsgDomain("order1",1L,"支付"),
                new MsgDomain("order1",1L,"发货"),
                new MsgDomain("order2",1L,"下单"),
                new MsgDomain("order2",1L,"支付"),
                new MsgDomain("order2",1L,"发货")
        );

        for (MsgDomain msg : msgList) {
            rocketMQTemplate.syncSendOrderly("bootOrderlyTopic",JSON.toJSONString(msg),msg.getOrderSn());
        }

    }

    @Override
    public void sendWithTag() {
        rocketMQTemplate.syncSend("bootTagTopic:tagA","一条带tag的消息");
    }

    @Override
    public void sendWithKey() {
        Message<String> message = MessageBuilder.withPayload("一条带key的消息").setHeader(RocketMQHeaders.KEYS, "kkkk").build();
        rocketMQTemplate.syncSend("bootKeyTopic",message);
    }

    @Override
    public void sendMode() {
        for (int i = 0; i < 10; i++) {
            rocketMQTemplate.syncSend("modeTopic","这是一条主体消息:"+i);
        }
    }
}
